package cn.keepme.ep.auth.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.jweb.core.bean.ReplyDataMode;
import org.jweb.core.query.hibernate.qbc.CriteriaQuery;
import org.jweb.core.util.Md5Util;
import org.jweb.core.util.MyBeanUtils;
import org.jweb.core.web.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.keepme.ep.auth.entity.TSUser;
import cn.keepme.ep.auth.transfer.form.authen.LoginForm;
import cn.keepme.ep.auth.transfer.vo.authen.AuthUserVO;
import cn.keepme.ep.auth.transfer.vo.authen.UserCategoryVO;
import cn.keepme.ep.common.entity.DictType;
import cn.keepme.ep.common.service.SysServiceI;
import cn.keepme.ep.member.entity.GeneralUserEntity;
import cn.keepme.ep.member.entity.UserCategoryEntity;
import cn.keepme.ep.member.transfer.form.member.UserCategorySearchForm;

/**
 * 登录登出功能控制器
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/authen")
public class AuthenController extends BaseController {

	@Autowired
	private SysServiceI sysService;
	
	@RequestMapping(value = "/login")
	@ResponseBody
	public ReplyDataMode login(LoginForm loginForm){
		ReplyDataMode j = new ReplyDataMode();
		
		Subject currentUser = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(
				loginForm.getCode(), Md5Util.getMD5(loginForm.getPwd()));
		token.setRememberMe(true);
		try {
			currentUser.login(token);
		} catch (AuthenticationException e) {
			j.setData("login errors");
			j.setSuccess(false);
			e.printStackTrace();
			return j;
		}
		if(currentUser.isAuthenticated()){
			ReplyDataMode jj = getUserInfo(loginForm.getCode());
			currentUser.getSession().setAttribute("userInfo", jj.getData());
			j.setData(jj.getData());
			j.setSuccess(true);
		}
		
		return j;
	}
	
	@RequestMapping(value = "/getUserInfo")
	@ResponseBody
	public ReplyDataMode getUserInfo(String mphone){
		ReplyDataMode j = new ReplyDataMode();
		GeneralUserEntity user = (GeneralUserEntity)sysService.findUniqueByProperty(GeneralUserEntity.class, "mphone", mphone);
		AuthUserVO userVO = new AuthUserVO();
		if(user == null){
			TSUser tsuser = sysService.findUniqueByProperty(TSUser.class, "mobilePhone", mphone);
			userVO.setEmail(tsuser.getEmail());
			userVO.setId(tsuser.getId());
			userVO.setMphone(tsuser.getMobilePhone());
			userVO.setNick(tsuser.getRealName());
			userVO.setUserType("b");//后台会员
		} else {
			try {
				MyBeanUtils.copyBean2Bean(userVO, user);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			userVO.setUserType("f");//前台会员
		}
		
		
		//根据当前会员获取喊单设置信息
		List<UserCategoryVO> ulist = getNotifySetingInfo(userVO.getMphone());
		userVO.setUlist(ulist);
		j.setData(userVO);
		j.setSuccess(true);
		
		return j;
	}
	
	private List<UserCategoryVO> getNotifySetingInfo(String mphone){
		List<UserCategoryVO> ulist = new ArrayList<UserCategoryVO>();
//		Subject currentUser = SecurityUtils.getSubject();
//		AuthUserVO userInfo = (AuthUserVO)currentUser.getSession().getAttribute("userInfo");
		
		AuthUserVO userInfo = new AuthUserVO();
		GeneralUserEntity gu = this.sysService.findUniqueByProperty(GeneralUserEntity.class, "mphone", mphone);
		if(gu == null){
			TSUser tsUser = this.sysService.findUniqueByProperty(TSUser.class, "mobilePhone", mphone);
			if(tsUser == null){
				return ulist;
			} else {
				userInfo.setEmail(tsUser.getEmail());
				userInfo.setId(tsUser.getId());
				userInfo.setMphone(mphone);
				userInfo.setNick(tsUser.getRealName());
				userInfo.setStatus(tsUser.getStatus().toString());
				userInfo.setUserType("b");
			}
		} else {
			userInfo.setEmail(gu.getEmail());
			userInfo.setId(gu.getId());
			userInfo.setMphone(mphone);
			userInfo.setNick(gu.getNick());
			userInfo.setStatus(gu.getStatus());
			userInfo.setUserType("f");
		}
		UserCategorySearchForm searchForm = new UserCategorySearchForm();
		searchForm.setUserId(userInfo.getId());
		searchForm.emptyValue2NullValue();
		CriteriaQuery cq = searchForm.getCriteriaQuery();
		List<UserCategoryEntity> userCategoryList = this.sysService.list(cq);
		
		List<DictType> dictTypeList = this.sysService.findDict("custom");
		Map<String,DictType> dictTypeMap = new HashMap<String,DictType>();
		for(DictType t : dictTypeList){
			dictTypeMap.put(t.getTypecode(), t);
		}
		
		//如果用户是初次设置，则初始化用户设置
		if(userCategoryList.isEmpty()){
			
			for(DictType dict : dictTypeList){
				UserCategoryEntity uc = new UserCategoryEntity();
				uc.setCategoryCode(dict.getTypecode());
				uc.setCategoryId(dict.getId());
				uc.setTradeRoomIdStatus("1");
				uc.setGeneralUserId(userInfo.getId());
				this.sysService.saveOrUpdate(uc);
			}
			
			userCategoryList = this.sysService.list(cq);
		}
		
		
		for(UserCategoryEntity l:userCategoryList){
			UserCategoryVO vo = new UserCategoryVO();
			vo.setCode(l.getCategoryCode());
			vo.setId(l.getId());
			DictType dictType = dictTypeMap.get(l.getCategoryCode());
			if(dictType != null){
				vo.setName(dictType.getTypename());
			}
			vo.setStatus(l.getTradeRoomIdStatus());
			ulist.add(vo);
		}
		return ulist;
		
//		try {
//			String sql = "select  t1.category_name,t1.category_code,t1.category_name,t2.general_user_id ,t2.category_id,t2.status,t2.id from tp_user_category t2   LEFT JOIN tp_analyze_category t1  on t2.category_id = t1.id where t2.status = '1' and t2.general_user_id = '" + mphone + "'";
//			List<Map<String,Object>> list  = sysService.findForJdbc(sql, null);
//			UserCategoryVO vo = new UserCategoryVO();
//			
//			for(Map<String,Object> l:list){
//				vo = new UserCategoryVO();
//				vo.setStatus(l.get("status").toString());
//				vo.setCode(l.get("category_code").toString());
//				vo.setName(l.get("category_name").toString());
//				ulist.add(vo);
//			}
//			
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		return ulist;
	}
	
	@RequestMapping(value = "/isLogin")
	@ResponseBody
	public ReplyDataMode isLogin(){
		ReplyDataMode j = new ReplyDataMode();
		
		Subject currentUser = SecurityUtils.getSubject();
		
		if(currentUser.isAuthenticated()){
			AuthUserVO user = (AuthUserVO)currentUser.getSession().getAttribute("userInfo");
			
			j.setData(user);
			j.setSuccess(true);
		} else {
			j.setSuccess(false);
			j.setData("no");
		}
		
		return j;
	}
	
	@RequestMapping(value = "/logout")
	@ResponseBody
	public ReplyDataMode logout(){
		ReplyDataMode j = new ReplyDataMode();
		
		Subject currentUser = SecurityUtils.getSubject();
		
		if(currentUser.isAuthenticated()){
			currentUser.logout();
			
		} 
		
		j.setData("successful");
		j.setSuccess(true);
		return j;
	}
	
	
}
